#ifndef HELPWIDGET_H
#define HELPWIDGET_H

#include <QWidget>
#include <QModelIndex>
#include <QStringListModel>
#include <QUrl>

#include "ui_helpwidget.h"

class QTextBrowser;
class QLineEdit;
class QComboBox;
class QListView;
class QDir;
class HelpNamesModel;
class HelpName;

class HelpWidget : public QWidget, public Ui::HelpWidget
{
    Q_OBJECT

public:
    enum LANGUAGE {LG_CORCPP, LG_PASCAL, LG_ALL, LG_NONE};

    static QDir getCHelpPath();
    static QDir getPasHelpPath();
    static void iniCHelpNames();
    static void iniPasHelpNames();
    static const QMap<QString, QStringList> *getCHelpNames();
    static const QMap<QString, QStringList> *getPasHelpNames();

    static HelpWidget *instance();
    static bool hasInstance();

public slots:
    void slotSetUrlSource(QUrl url);
    void slotSetSource(QString &url);
    void slotSearch();
    void slotSearch(const QString &);

protected:
    virtual void closeEvent ( QCloseEvent * event );

private:
    static HelpWidget *m_instance;

    static QMap<QString, QStringList> *cHelpNames;
    static QMap<QString, QStringList> *pasHelpNames;

    QLineEdit *m_addrLine;
    HelpNamesModel *model;
    QStringList displayNames;

    QString searchKey;
    LANGUAGE language;

    const static QString CORCPPSTRING;
    const static QString PASCALSTRING;
    const static QString ALLSTRING;

private slots:
    void slotBack();
    void slotForward();
    void slotHome();
    void slotRefresh();
    void slotAddrReturnPressed();
    void slotChange(QString);
    void displayHelpFile(QModelIndex);

private:
    HelpWidget( QWidget* = 0 );

    void recordUrl(QString &addr);
    void displayHelpFileNames();
};

class HelpNamesModel : public QAbstractListModel
{
public:
    HelpNamesModel ( QObject *p);
    HelpNamesModel ( const QString & key, const HelpWidget::LANGUAGE &lg, QObject * parent = 0 );

    int rowCount(const QModelIndex &parent = QModelIndex()) const;

    QVariant data(const QModelIndex &index, int role) const;

    Qt::ItemFlags flags(const QModelIndex &index) const;

    bool insertRows(int row, int count, const QModelIndex &parent = QModelIndex());
    bool removeRows(int row, int count, const QModelIndex &parent = QModelIndex());

    void sort(int column, Qt::SortOrder order = Qt::AscendingOrder);

    void setKey(const QString &key, const HelpWidget::LANGUAGE &language);
private:
    QList<HelpName> lst;
    QHash<int, QString> cHash;
    QHash<int, QString> pasHash;
    QString key;
};

class HelpName
{
public:
    HelpName(QString s, HelpWidget::LANGUAGE l);
    inline QString getName() const { return name; }
    inline HelpWidget::LANGUAGE getLanguage() const { return language; }
    inline bool operator<(HelpName &other) {return name < other.getName(); }
private:
    QString name;
    HelpWidget::LANGUAGE language;
};

#endif // HELPWIDGET_H
